using System.Reflection;
using Blazored.LocalStorage;
using BlazorPro.BlazorSize;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using StudentVideo.Client;
using StudentVideo.Client.Common.Interfaces;
using StudentVideo.Client.Handler;
using StudentVideo.Client.Services;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
// 加载环境变量文件
builder.Configuration
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{builder.HostEnvironment.Environment}.json", optional: true, reloadOnChange: true);

builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddBlazoredLocalStorage();
builder.Services.AddMediaQueryService();
builder.Services.AddResizeListener();
builder.Services.AddAntDesign();

builder.Services.AddSingleton<PageLoadingService>();

#region 动态注入所有 IService 实现类
var allServices = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(assembly => {
       try {
          return assembly.GetTypes();
       } catch (ReflectionTypeLoadException) {
          return [];
       }
    })
    .Where(t =>
        t.IsClass &&
        !t.IsAbstract &&
        typeof(IHttpRouter).IsAssignableFrom(t)
    )
    .ToList();

foreach (var type in allServices) {
   // 注册实现类自身类型
   builder.Services.AddScoped(type);

   // 注册其实现的特定接口（排除 IService）
   var interfaces = type.GetInterfaces().Where(i => i != typeof(IHttpRouter));
   foreach (var interfaceType in interfaces) {
      builder.Services.AddScoped(interfaceType, type);
   }
}
#endregion

builder.Services.AddScoped<JsInteropService>();
builder.Services.AddScoped<BearerTokenHandler>();

// 注册自定义 Http 服务
builder.Services
   .AddHttpClient<HttpHandler>(sp => { sp.BaseAddress = new Uri(builder.Configuration["ApiBaseUrl"]!); })
   .AddHttpMessageHandler<BearerTokenHandler>();

await builder.Build().RunAsync();
